package com.dayanxs.Service;

import com.dayanxs.Utils.AESCryptoUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class NovelService {

    private final JdbcTemplate jdbcTemplate;
    private final SimpleDateFormat dateFormatter;

    public NovelService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定时间格式
    }

    // 增加小说
    public ResponseEntity<?> addNovel(String authorization, Map<String, String> novelDetails) {
        try {
            // 检查 Authorization 头部
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                return ResponseEntity.status(201).body(Map.of("message", "Bearer token missing or invalid"));
            }

            // 从 Authorization 中提取 Bearer 令牌
            String userToken = authorization.substring(7); // 去掉 "Bearer " 前缀
            // 解密 userToken
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];

            // 查询用户ID
            String sql = "SELECT id FROM user WHERE username = ?";
            Integer authorId = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);

            // 检查 novel_name 长度
            String novelName = novelDetails.get("novel_name");
            if (novelName == null || novelName.length() > 50) {
                return buildErrorResponse("小说名称标题过长，不得超过五十个字！", 201);
            }
            // 检查小说名称是否重复
            sql = "SELECT COUNT(*) FROM novel WHERE novel_name = ?";
            int nameCount = jdbcTemplate.queryForObject(sql, new Object[]{novelName}, Integer.class);

            if (nameCount > 0) { // 名字重复
                return buildErrorResponse("已经有书叫这个名字了，换一个吧 ~", 201);
            }
            // 检查 novel_type 长度
            String novelType = novelDetails.get("novel_type");
            if (novelType != null && novelType.length() > 20) {
                return buildErrorResponse("小说类型不得超过二十个字！", 201);
            }

            // 插入小说
            sql = "INSERT INTO novel (novel_name, novel_desc, novel_authorID, novel_type, novel_pic, novel_state) VALUES (?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(sql, novelName, novelDetails.get("novel_desc"), authorId, novelType, novelDetails.get("novel_pic"), 0);

            return buildSuccessResponse("小说添加成功");

        } catch (Exception e) {
            return buildErrorResponse("Error adding novel: " + e.getMessage(), 500);
        }
    }

    // 查询随机30条小说
    public ResponseEntity<?> getRandomNovels() {
        try {
            // 查询30条随机小说
            String novelQuery = "SELECT * FROM novel ORDER BY RAND() LIMIT 30";
            List<Map<String, Object>> novels = jdbcTemplate.queryForList(novelQuery);

            // 获取所有 novel_authorID
            Set<Integer> authorIDs = new HashSet<>();
            for (Map<String, Object> novel : novels) {
                Integer authorID = (Integer) novel.get("novel_authorID");
                if (authorID != null) {
                    authorIDs.add(authorID);
                }
            }

            // 查询所有对应的作者信息
            Map<Integer, Map<String, Object>> authorMap = new HashMap<>();
            for (Integer authorID : authorIDs) {
                String sql = "SELECT nickname, introduce FROM user WHERE id = ?";
                List<Map<String, Object>> authorList = jdbcTemplate.queryForList(sql, new Object[]{authorID});

                if (!authorList.isEmpty()) { // 检查是否为空
                    authorMap.put(authorID, authorList.get(0));
                } else { // 如果作者ID没有找到，返回默认值
                    Map<String, Object> defaultAuthor = new HashMap<>();
                    defaultAuthor.put("nickname", "作者没有找到");
                    defaultAuthor.put("introduce", "作者没有找到");
                    authorMap.put(authorID, defaultAuthor);
                }
            }

            // 将作者信息添加到小说数据中
            for (Map<String, Object> novel : novels) {
                Integer authorID = (Integer) novel.get("novel_authorID");
                if (authorMap.containsKey(authorID)) {
                    novel.put("novel_author", authorMap.get(authorID));
                } else {
                    Map<String, Object> defaultAuthor = new HashMap<>();
                    defaultAuthor.put("nickname", "作者没有找到");
                    defaultAuthor.put("introduce", "作者没有找到");
                    novel.put("novel_author", defaultAuthor);
                }
                novel.remove("novel_authorID"); // 移除原始的作者ID
            }

            return ResponseEntity.ok(novels);

        } catch (Exception e) {
            return buildErrorResponse("Error fetching novels: " + e.getMessage(), 500);
        }
    }

    // 查询小说通过名字
    public ResponseEntity<?> searchNovels(String novelName) {
        try {
            // 查询小说数据
            String sql = "SELECT * FROM novel WHERE novel_name LIKE ?";
            List<Map<String, Object>> novels = jdbcTemplate.queryForList(sql, new Object[]{"%" + novelName + "%"});

            if (novels.isEmpty()) {
                return ResponseEntity.ok(Collections.emptyList());
            }

            // 提取所有 unique 的 novel_authorID
            Set<Integer> authorIDs = new HashSet<>();
            for (Map<String, Object> novel : novels) {
                Integer authorID = (Integer) novel.get("novel_authorID");
                if (authorID != null) {
                    authorIDs.add(authorID);
                }
            }

            // 查询作者信息
            Map<Integer, Map<String, Object>> authorMap = new HashMap<>();
            for (Integer authorID : authorIDs) {
                String authorSql = "SELECT nickname, introduce FROM user WHERE id = ?";
                List<Map<String, Object>> authorList = jdbcTemplate.queryForList(authorSql, new Object[]{authorID});

                if (!authorList.isEmpty()) { // 如果找到作者
                    authorMap.put(authorID, authorList.get(0));
                } else { // 如果没有找到，设置默认值
                    Map<String, Object> defaultAuthor = new HashMap<>();
                    defaultAuthor.put("nickname", "作者没有找到");
                    defaultAuthor.put("introduce", "作者没有找到");
                    authorMap.put(authorID, defaultAuthor);
                }
            }

            // 将作者信息添加到小说数据中
            for (Map<String, Object> novel : novels) {
                Integer authorID = (Integer) novel.get("novel_authorID");
                if (authorMap.containsKey(authorID)) {
                    novel.put("novel_author", authorMap.get(authorID));
                } else { // 处理异常情况
                    Map<String, Object> defaultAuthor = new HashMap<>();
                    defaultAuthor.put("nickname", "作者没有找到");
                    defaultAuthor.put("introduce", "作者没有找到");
                    novel.put("novel_author", defaultAuthor);
                }
                novel.remove("novel_authorID"); // 移除原始的作者ID
            }

            return ResponseEntity.ok(novels);

        } catch (Exception e) {
            return buildErrorResponse("Error searching novels: " + e.getMessage(), 500);
        }
    }

    // 删除小说通过ID
    public ResponseEntity<?> deleteNovel(int novelId, String authorization) {
        try {

            // 从 Authorization 中提取 Bearer 令牌
            String userToken = getToken(authorization); // 去掉 "Bearer " 前缀
            // 解密 userToken
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];
            String sql = null;

            if (!isAdmin(username)) {
                // 查询用户ID
                sql = "SELECT id FROM user WHERE username = ?";
                Integer userId = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);

                // 检查小说是否属于当前用户
                sql = "SELECT novel_authorID FROM novel WHERE novel_id = ?";
                Integer authorId = jdbcTemplate.queryForObject(sql, new Object[]{novelId}, Integer.class);

                if (!Objects.equals(userId, authorId)) {
                    return buildErrorResponse("你不是这个小说的拥有者！", 201);
                }
            }

            // 删除小说
            sql = "DELETE FROM novel WHERE novel_id = ?";
            jdbcTemplate.update(sql, novelId);

            sql = "DELETE FROM novel_chapter WHERE chapter_novelID = ?";
            jdbcTemplate.update(sql, novelId);

            return buildSuccessResponse("小说和章节全部删除成功！");

        } catch (Exception e) {
            return buildErrorResponse("Error deleting novel: " + e.getMessage(), 500);
        }
    }

    // 更新小说
    public ResponseEntity<?> updateNovel(int novelId, String authorization, Map<String, String> novelDetails) {
        try {
            String userToken = getToken(authorization);
            // 解密 userToken
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];
            String sql = null;

            if (!isAdmin(username)) {
                // 查询用户ID
                sql = "SELECT id FROM user WHERE username = ?";
                Integer userId = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);

                // 检查小说是否属于当前用户
                sql = "SELECT novel_authorID FROM novel WHERE novel_id = ?";
                Integer authorId = jdbcTemplate.queryForObject(sql, new Object[]{novelId}, Integer.class);

                if (!Objects.equals(userId, authorId)) {
                    return buildErrorResponse("这本小说不是你的！", 201);
                }
            }
            // 检查 novel_name 长度
            String novelName = novelDetails.get("novel_name");
            if (novelName == null || novelName.length() > 50) {
                return buildErrorResponse("小说名称为空或标题过长，不得超过五十个字！", 201);
            }
            // 检查小说名称是否重复
            sql = "SELECT COUNT(*) FROM novel WHERE novel_name = ? and novel_id != ?";
            int nameCount = jdbcTemplate.queryForObject(sql, new Object[]{novelName,novelId}, Integer.class);

            if (nameCount > 0) { // 名字重复
                return buildErrorResponse("已经有书叫这个名字了，换一个吧 ~", 201);
            }
            // 检查 novel_type 长度
            String novelType = novelDetails.get("novel_type");
            if (novelType != null && novelType.length() > 20) {
                return buildErrorResponse("小说类型不得超过二十个字！", 201);
            }
            // 更新小说
            sql = "UPDATE novel SET novel_name = ?, novel_desc = ?, novel_type = ?, novel_pic = ? WHERE novel_id = ?";
            jdbcTemplate.update(sql, novelName, novelDetails.get("novel_desc"), novelType, novelDetails.get("novel_pic"), novelId);

            return buildSuccessResponse("小说信息更新成功！");

        } catch (Exception e) {
            return buildErrorResponse("Error updating novel: " + e.getMessage(), 500);
        }
    }
    public ResponseEntity<?> getNovelById(int novelId) {
        try {
            // 查询小说信息
            String novelQuery = "SELECT * FROM novel WHERE novel_id = ?";
            List<Map<String, Object>> novelList = jdbcTemplate.queryForList(novelQuery, new Object[]{novelId});

            if (novelList.isEmpty()) { // 如果没有找到小说
                return buildErrorResponse("小说没有找到！", 201);
            }
            //获取作品的最新章ID号
            String firstChapterIdQuery = "SELECT `id`,`chapter_title`,`update_time` FROM novel_chapter WHERE chapter_novelID = ? ORDER BY update_time DESC LIMIT 1";
            List<Map<String, Object>> firstChapterIdList = jdbcTemplate.queryForList(firstChapterIdQuery, new Object[]{novelId});
            // 优化时间格式
            for (Map<String, Object> chapter : firstChapterIdList) {
                Object updateTime = chapter.get("update_time");
                if (updateTime instanceof Date) {
                    chapter.put("update_time", dateFormatter.format((Date) updateTime)); // 格式化时间
                }
            }
            Map<String, Object> novel = novelList.get(0);
            if(!firstChapterIdList.isEmpty()) {
                //存放作品第一章ID
                novel.put("latest_chapter", firstChapterIdList.get(0));
            }else{
                novel.put("latest_chapter", null);
            }

            // 查询作者信息
            Integer authorID = (Integer) novel.get("novel_authorID");
            String authorQuery = "SELECT nickname, introduce FROM user WHERE id = ?";
            List<Map<String, Object>> authorList = jdbcTemplate.queryForList(authorQuery, new Object[]{authorID});

            Map<String, Object> authorInfo;
            if (!authorList.isEmpty()) { // 如果找到作者信息
                authorInfo = authorList.get(0);
            } else { // 如果没有找到作者
                authorInfo = new HashMap<>();
                authorInfo.put("nickname", "Author not found");
                authorInfo.put("introduce", "Author not found");
            }

            // 将作者信息添加到小说数据中
            novel.put("novel_author", authorInfo);
            novel.remove("novel_authorID"); // 移除原始的作者ID
            return ResponseEntity.ok(novel);

        } catch (Exception e) { // 捕获异常并返回 HTTP 500 错误
            return buildErrorResponse("Error retrieving novel: " + e.getMessage(), 500);
        }
    }
    public ResponseEntity<?> getNovelsWithPagination(int size, int page) {
        try {
            // 计算总记录数
            String countSql = "SELECT COUNT(*) FROM novel";
            Integer totalRecords = jdbcTemplate.queryForObject(countSql, Integer.class); // 总记录数

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalRecords / size); // 总页数

            // 计算 OFFSET
            int offset = (page - 1) * size;

            // 分页查询
            String sql = "SELECT * FROM novel ORDER BY novel_id DESC LIMIT ? OFFSET ?";
            List<Map<String, Object>> novels = jdbcTemplate.queryForList(sql, new Object[]{size, offset});

            // 遍历每个小说，查询其作者信息
            for (Map<String, Object> novel : novels) {
                Integer authorID = (Integer) novel.get("novel_authorID");

                // 查询作者信息
                String authorSql = "SELECT nickname, introduce FROM user WHERE id = ?";
                List<Map<String, Object>> authorList = jdbcTemplate.queryForList(authorSql, new Object[]{authorID});

                if (!authorList.isEmpty()) {
                    Map<String, Object> author = authorList.get(0); // 获取作者信息
                    novel.put("novel_author", author); // 添加到 novel 对象
                } else {
                    // 如果作者信息未找到，设置默认值
                    Map<String, Object> defaultAuthor = new HashMap<>();
                    defaultAuthor.put("nickname", "未知");
                    defaultAuthor.put("introduce", "没有找到相关介绍");
                    novel.put("novel_author", defaultAuthor);
                }

                novel.remove("novel_authorID"); // 移除原始的 author ID
            }
            Map<String, Object> response = new HashMap<>();
            response.put("totalPages", totalPages); // 总页数
            response.put("novels", novels); // 小说数据

            return ResponseEntity.ok(response); // 返回分页结果和总页数

        } catch (Exception e) {
            // 错误处理
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "Error fetching novels: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    public ResponseEntity<?> addNovelAndChapter(Map<String, String> data) {
        try {
            // 获取输入参数
            String novelName = data.getOrDefault("novel_name", "").trim();
            String chapterTitle = data.getOrDefault("chapter_title", "").trim();
            String chapterContent = data.getOrDefault("chapter_content", "").trim();
            String chapterTimeStr = data.getOrDefault("chapter_time", "").trim();

            // 检查时间格式
            Timestamp chapterTime;
            try {
                chapterTime = Timestamp.valueOf(chapterTimeStr);
            } catch (IllegalArgumentException e) {
                return ResponseEntity.status(201).body(Map.of("message", "章节时间格式无效！"));
            }

            // 检查小说是否存在
            String checkNovelSql = "SELECT novel_id FROM novel WHERE novel_name = ?";
            Optional<Integer> novelIdOpt = jdbcTemplate.query(checkNovelSql,
                    new Object[]{novelName},
                    rs -> rs.next() ? Optional.of(rs.getInt("novel_id")) : Optional.empty()
            );

            if (novelIdOpt.isEmpty()) {
                // 如果小说不存在，创建
                Random rand = new Random();
                int randomAuthorId = rand.nextInt(5) + 1;
                String[] genres = {"历史", "玄幻", "仙侠"};
                String randomGenre = genres[rand.nextInt(genres.length)];

                String insertNovelSql = "INSERT INTO novel (novel_name, novel_desc, novel_authorID, novel_type, novel_pic, novel_state) " +
                        "VALUES (?, '还没有描述', ?, ?, '图片正在上传中', 0)";
                jdbcTemplate.update(insertNovelSql, novelName, randomAuthorId, randomGenre);

                // 再次查询确保获得 novel_id
                novelIdOpt = jdbcTemplate.query(checkNovelSql,
                        new Object[]{novelName},
                        rs -> rs.next() ? Optional.of(rs.getInt("novel_id")) : Optional.empty()
                );
            }

            if (novelIdOpt.isEmpty()) {
                return ResponseEntity.status(500).body(Map.of("message", "获取小说 ID 失败！"));
            }

            int novelId = novelIdOpt.get();

            // 检查是否已有相同章节标题
            String checkChapterSql = "SELECT COUNT(*) FROM novel_chapter WHERE chapter_novelID = ? AND chapter_title = ?";
            int existingChapterCount = jdbcTemplate.queryForObject(checkChapterSql,
                    new Object[]{novelId, chapterTitle},
                    Integer.class
            );

            if (existingChapterCount > 0) {
                // 章节重复，返回信息
                return ResponseEntity.status(409).body(Map.of("message", "小说下章节标题重复，已跳过！"));
            }

            // 检查上一章的时间
            String getLastChapterTimeSql = "SELECT update_time FROM novel_chapter WHERE chapter_novelID = ? ORDER BY update_time DESC LIMIT 1";
            Optional<Timestamp> lastChapterTimeOpt = jdbcTemplate.query(getLastChapterTimeSql,
                    new Object[]{novelId},
                    rs -> rs.next() ? Optional.of(rs.getTimestamp("update_time")) : Optional.empty()
            );

            // 如果传入的时间不比上一章晚，调整
            Timestamp lastChapterTime = lastChapterTimeOpt.orElse(new Timestamp(System.currentTimeMillis()));
            if (!chapterTime.after(lastChapterTime)) {
                chapterTime = new Timestamp(lastChapterTime.getTime() + 1000); // 加一秒
            }

            // 插入新章节
            String insertChapterSql = "INSERT INTO novel_chapter (chapter_title, chapter_content, update_time, chapter_novelID) " +
                    "VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(insertChapterSql, chapterTitle, chapterContent, chapterTime, novelId);

            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "小说和章节保存成功！");
            return ResponseEntity.ok(successResponse);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "数据库操作失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    private String getToken(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return "";
        }
        // 从 Authorization 中提取 Bearer 令牌
        return authorization.substring(7);
    }
    public boolean isAdmin(String username) {
        try {
            // 查询用户是否是管理员
            String sql = "SELECT 1 FROM admin WHERE username = ?";
            jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);
            // 如果查询成功执行到这里，说明用户是管理员
            return true;
        } catch (EmptyResultDataAccessException e) {
            // 用户不存在于admin表中，返回false
            return false;
        } catch (Exception e) {
            // 处理其他可能的异常，例如数据库连接问题等
            // 这里可能需要记录日志或抛出更具体的异常
            // 但在当前的上下文中，我们简单地返回false
            return false;
        }
    }

    private ResponseEntity<Map<String, String>> buildErrorResponse(String message, int status) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", message);
        return ResponseEntity.status(status).body(errorResponse);
    }

    private ResponseEntity<Map<String, String>> buildSuccessResponse(String message) {
        Map<String, String> successResponse = new HashMap<>();
        successResponse.put("message", message);
        return ResponseEntity.ok(successResponse);
    }


}
